package dao;

import model.Customer;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @program: foodApp
 * @description: customer control mysql
 * @author: PanKer
 * @create: 2021-11-20 00:12
 */
public class customerDao {

    public static boolean isExist(Connection conn, String username) throws SQLException {
        String sql = "SELECT * FROM customer WHERE UserName = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, username);
        ResultSet rs = ps.executeQuery();

        return rs.next();
    }

    public static Customer login(Connection conn, Customer customer) throws SQLException {
        String sql = "SELECT * FROM customer WHERE UserName = ? and PassWord = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, customer.getUsername());
        ps.setString(2, customer.getPassword());
        ResultSet rs = ps.executeQuery();

        if (rs.next()) {
            Customer resultCustomer = new Customer(
                    rs.getString("UserName"),
                    rs.getString("PassWord"),
                    rs.getString("Address"),
                    rs.getString("Email"),
                    rs.getString("Telephone"),
                    rs.getString("Date")
            );
            return resultCustomer;
        } else return null;
    }

    public static int add(Connection conn, Customer customer) throws SQLException {
        String sql = "INSERT INTO `customer` VALUES (?, ?, ?, ?, ?, ?, NULL)";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1, customer.getUsername());
        ps.setString(2, customer.getPassword());
        ps.setString(3, customer.getAddress());
        ps.setString(4, customer.getEmail());
        ps.setString(5, customer.getTel());
        ps.setString(6, customer.getDate());

        return ps.executeUpdate();          // 返回值是受影响的行数
    }
}
